package models

import (
	"github.com/goravel/framework/database/orm"
	"github.com/goravel/framework/facades"
)

type Role struct {
	orm.Model
	RoleName    string `json:"role_name"`
	Description string `json:"description"`
	orm.SoftDeletes
	orm.Timestamps

	// 关联关系
	Users       []User       `json:"users" gorm:"many2many:user_roles;"`
	Permissions []Permission `json:"permissions" gorm:"many2many:role_permissions;"`
}

func (r *Role) TableName() string {
	return "roles"
}

// GetUsers 获取角色下的用户
func (r *Role) GetUsers() ([]User, error) {
	var users []User
	err := facades.Orm().Query().
		Table("users").
		Join("user_roles", "users.id", "=", "user_roles.user_id").
		Where("user_roles.role_id", r.ID).
		Find(&users)
	return users, err
}

// GetPermissions 获取角色的权限
func (r *Role) GetPermissions() ([]Permission, error) {
	var permissions []Permission
	err := facades.Orm().Query().
		Table("permissions").
		Join("role_permissions", "permissions.id", "=", "role_permissions.permission_id").
		Where("role_permissions.role_id", r.ID).
		Find(&permissions)
	return permissions, err
}

// HasPermission 检查角色是否有指定权限
func (r *Role) HasPermission(permissionKey string) (bool, error) {
	var count int64
	err := facades.Orm().Query().
		Table("roles").
		Join("role_permissions", "roles.id", "=", "role_permissions.role_id").
		Join("permissions", "role_permissions.permission_id", "=", "permissions.id").
		Where("roles.id", r.ID).
		Where("permissions.perm_key", permissionKey).
		Count(&count)

	return count > 0, err
}
